const db = require("../db/index")

// 获取文章列表
let cates = (req, res) => {
    // 获取数据
    const sql = "select * from ev_article_cate where is_delete=0"
    db.query(sql, (err, result) => {
        if (err) return res.cc(err)
        res.send({
            status: 0,
            message: "获取文章分类成功",
            data:result
        })
    })
}
// 添加文章分类
let addCates = (req, res) => {
    const sql = "select * from ev_article_cate where name=? or alias=?"
    db.query(sql, [req.body.name, req.body.alias], (err, result) => {
        if (err) return res.cc(err)
        if (result.length == 2) return res.cc("分类名称与分类别名被占用")
        if (result.length == 1 && result[0].name == req.body.name && result[0].alias == req.body.alias) return res.cc("分类名称与分类别名被占用")
        if (result.length == 1 && result[0].name == req.body.name) return res.cc("分类名称被占用")
        if (result.length == 1 && result[0].alias == req.body.alias) return res.cc("分类别名被占用")
        const sqlStr = "insert into ev_article_cate set ?"
        db.query(sqlStr, req.body, (err, result) => {
            if (err) return res.cc(err)
            if (result.affectedRows !== 1) return res.cc("添加失败")
            res.cc("添加分类成功",0)
        })
    })
}
// 根据 id 删除文章分类
let removeCates = (req, res) => {
    const sql = `update ev_article_cate set is_delete=1 where id=?`
    db.query(sql, req.params.id ,(err, result) => {
        if (err) return res.cc(err)
        if (result.affectedRows !== 1) return res.cc("删除文章分类失败")
        res.cc("删除文章分类成功",0)
    })
    
}
// 根据 id 获取文章分类
let getArticleById = (req, res) => {
    const sql = `select * from ev_article_cate where id=? and is_delete=0`
    db.query(sql, req.params.id, (err, result) => {
        if (err) return res.cc(err)
        // sql语句执行成功 但是未找到数据
        if (result.length !== 1) return res.cc("获取文章分类失败")
        res.send({
            status: 0,
            message: "获取文章分类成功",
            data:result[0]
        })
    })
}
// 根据 id 更新文章分类
let updateCateById = (req, res) => {
    const sql = "select * from ev_article_cate where id !=? and (name=? or alias=?)"
    db.query(sql, [req.body.id,req.body.name, req.body.alias], (err, result) => {
        if (err) return res.cc(err)
        if (result.length == 2) return res.cc("分类名称与分类别名被占用")
        if (result.length == 1 && result[0].name == req.body.name && result[0].alias == req.body.alias) return res.cc("分类名称与分类别名被占用")
        if (result.length == 1 && result[0].name == req.body.name) return res.cc("分类名称被占用")
        if (result.length == 1 && result[0].alias == req.body.alias) return res.cc("分类别名被占用")
        const sql = "update ev_article_cate set ? where id=?"
        db.query(sql, [req.body, req.body.id], (err, result) => {
            if (err) return res.cc(err)
            if (result.affectedRows !== 1) return res.cc("更新文章分类失败")
            res.cc("更新文章分类成功",0)
        })
    })
}


module.exports = {
    cates,
    addCates,
    removeCates,
    getArticleById,
    updateCateById,

}